<?php

class DefaultController extends Controller
{
	public function actionIndex()
	{	
		$this->render('index');
	}
	
	public function actionLogin()
	{
		$model = new LoginForm;
		
		$this->renderPartial('login', array(
			'model'=>$model
		));
	}
	
	public function actionRecover()
	{
		$model = new Members('recover');
		
		$this->renderPartial('recover', array(
			'model'=>$model
		));
	}
	
	public function actionAuthenticate()
	{
		$this->layout = '//layouts/usersDefaultAuth';
		$login = new LoginForm;
		$register = new Members('register');
		
		// Login process
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($login);
			Yii::app()->end();
		}

		if(isset($_POST['LoginForm']))
		{
			$login->attributes=$_POST['LoginForm'];
			if($login->validate() && $login->login()) {
				$this->redirect(Yii::app()->user->returnUrl);
			}
		}
		
		// Register process
		if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
		{
			echo CActiveForm::validate($register);
			Yii::app()->end();
		}
		
		if(isset($_POST['Members']))
		{
			$register->attributes=$_POST['Members'];
			$register->dateofbirth = date('Y-m-d', strtotime($register->dateofbirth));
			$register->image = 'noavatar.jpg';
			$register->phone = '';
			$register->altphone = '';
			$register->address = '';
			$register->city = '';
			$register->country = '';
			$register->totalpoints = 0;
			$register->newsletter = 'Y';
			$register->type = 'E';
			$register->status = 'A';
			$register->lastlogin = $register->createddate = date('Y-m-d H:i:s');
			$register->oldsalt = '';
			$register->oldpassword = '';

            if ($register->validate()) {
				$register->password = $register->confirmPassword = CPasswordHelper::hashPassword($register->password);
                if ($register->save()) {
                    // Save logs
                    $log = new Logs;
                    $log->user_id = Yii::app()->user->id;
                    $log->message = 'là thành viên mới của NexttopEvent.';
                    $log->type = 'U';
                    $log->posteddate = date('Y-m-d H:i:s');
                    $log->save();
	                Yii::app()->user->setFlash('register', "Đăng ký tài khoản mới thành công. Vui lòng đăng nhập để sử dụng dịch vụ.");
					$this->redirect(Yii::app()->user->returnUrl);
				}
            }
		}
		
		// Render authenticate
		$this->render('authenticate', array(
			'login'=>$login,
			'register'=>$register
		));
	}
	
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}